<?php

/**
 * uniBoard ACP Smileys Import/Export tool
 *
 * Light and fast forum solution for web 2.0-like communities.
 *
 * @package		uniBoard
 * @author		Rafał Pitoń
 * @license		http://www.gnu.org/licenses/gpl-3.0.html
 * @since		Version 0.1
 * 
 * ------------------------------------------------------------------------
 * 
 * $Date: 2010-09-20 21:23:27 +0000 (Mon, 20 Sep 2010) $
 * $Revision: 64 $
 * $Author: rafio.xudb@gmail.com $
 */

// ------------------------------------------------------------------------

class action_smileys_impexp{
	
	/**
	 * Main class pointer
	 *
	 * @var object
	 */
	
	private $appCore		= NULL;
	
	// ------------------------------------------------------------------------

	/**
	 * Initialise Action
	 *
	 * @param object $appCore
	 */
	
	function __construct( $appCore){
		
		// Store appCore pointer
		$this -> appCore = $appCore;
		
		// What to do?
		if ( $appCore -> _POST( 'import') == 1)
		{
			// Do Import
			$this -> makeImport();
		}
		else if ( $appCore -> _POST( 'export') == 1)
		{
			// Do Export
			$this -> makeExport();
		}
		else
		{
			// Draw forms
			$this -> drawForms();
		}
	}

	// ------------------------------------------------------------------------

	/**
	 * Performs Import
	 *
	 */
	
	function makeImport(){
		
		// Create file upload
		$data_file = new api_file_upload( $this -> appCore, 'data_file');
		
		// Configure uploaded
		$data_file -> setExtensions( array( '.xml', '.xml.gz'));
		$data_file -> setUploadSize( 12288);
		
		// Catch file
		$data_file -> catchFile();
		
		// Try-catch
		try
		{
			// Api has error?
			if ( $data_file -> error)
			{
				// Trow exception
				throw new exc_small( $data_file -> last_error);
			}
				
			// Detect if we uploaded file is GZIP compressed
			if ( strtolower( substr( $data_file -> getFileName(), strlen( $data_file -> getFileName()) - 7)) == '.xml.gz')
			{
				// Uncompress file
				if ( function_exists( 'gzfile'))
				{
					$data_file = join( '', gzfile( $data_file -> getFilePath()));
				}
				else
				{
					// Trow exception
					throw new exc_small( $this -> appCore -> lang['acp_imageset_import_gzip_not_avaiable']);
				}
			}
			else
			{
				// Simply load XML file contents
				$data_file = file_get_contents( $data_file -> getFilePath());
			}
			
			// We will handle errors
			libxml_use_internal_errors(false);
			
			// Create xml data file
			@$data = simplexml_load_string( $data_file);
			
			// Error?
			if ( $data === false)
			{
				// Trow exception
				throw new exc_small( $this -> appCore -> lang['acp_import_xml_corrupted']);
			}
			
			// Data is valid?
			if ( !isset( $data -> smileys))
			{
				throw new exc_small( $this -> appCore -> lang['acp_import_xml_corrupted']);
			}
			
			// File insert
			$insert_sql = array();
			
			// Collisions mode
			$collisions_handling = (int) $this -> appCore -> _POST( 'collisions_mode');
			
			// Reiterate images
			foreach ( $data -> smileys -> smiley as $smiley_data)
			{
				// Image has correct data?
				if ( isset( $smiley_data -> smiley_replace) && isset( $smiley_data -> smiley_image) && isset( $smiley_data -> smiley_file) && isset( $smiley_data -> smiley_width) && isset( $smiley_data -> smiley_height) && isset( $smiley_data -> smiley_name) && isset( $smiley_data -> smiley_in_editor))
				{
					// Decode data
					$smiley_replace = base64_decode( $smiley_data -> smiley_replace);
					$smiley_image = base64_decode( $smiley_data -> smiley_image);
					$smiley_file = base64_decode( $smiley_data -> smiley_file);
					$smiley_width = (int) base64_decode( $smiley_data -> smiley_width);
					$smiley_height = (int) base64_decode( $smiley_data -> smiley_height);
					$smiley_name = base64_decode( $smiley_data -> smiley_name);
					$smiley_in_editor = (bool) base64_decode( $smiley_data -> smiley_in_editor);
										
					// File content is good?
					if ( isset( $smiley_file[0]) && isset( $smiley_replace[0]) && mb_strlen( $smiley_replace) < 256 && isset( $smiley_image[0]) && mb_strlen( $smiley_image) < 256 && isset( $smiley_name[0]) && mb_strlen( $smiley_name) < 256)
					{
						// Fix width
						if ( $smiley_width < 1)
						{
							$smiley_width = 1;
						}
						
						// Fix height
						if ( $smiley_height < 1)
						{
							$smiley_height = 1;
						}
						
						// File name is allrite?
						$file_name = $this -> appCore -> secureFilename( substr( $smiley_image, 0, strpos( $smiley_image, '.')));
						$file_ext = strtolower( substr( $smiley_image, strpos( $smiley_image, '.')));
						
						// Extension checks out?
						if ( $file_ext == '.png' || $file_ext == '.gif' || $file_ext == '.jpeg' || $file_ext == '.jpg')
						{
							// Build complete filename
							$smiley_image = $file_name . $file_ext;
							
							// File name checks?
							if ( isset( $smiley_image[0]) && mb_strlen( $smiley_image) < 256)
							{
								// Handle collision?
								if ( file_exists( SMILEYS_PATH . $smiley_image))
								{
									if ( $collisions_handling == 2)
									{
										// New name
										$smiley_image_new = '1_' . $smiley_image;
										
										// Fix integer
										$i = 1;
										
										// Reiterate
										while ( file_exists( SMILEYS_PATH . $smiley_image_new))
										{
											// New name
											$smiley_image_new = '1_' . $smiley_image;
											
											// Fix integer
											$i ++;
										}
										
										// Add file to massinsert
										$insert_sql[] = '\'' .  $this -> appCore -> db -> strEscape( $smiley_replace) . '\', \'' . $this -> appCore -> db -> strEscape( $smiley_image_new) . '\', \'' . $smiley_width . '\', \'' . $smiley_height . '\', \'' . $this -> appCore -> db -> strEscape( $smiley_name) . '\', \'' . $smiley_in_editor . '\'';
									
										// Make file
										file_put_contents( SMILEYS_PATH . $smiley_image_new, $smiley_file);
									}
									else if ( $collisions_handling == 1)
									{
										// Replace file with new one
										file_put_contents( SMILEYS_PATH . $smiley_image, $smiley_file);
									}
								}
								else
								{
									// Add file to massinsert
									$insert_sql[] = '\'' .  $this -> appCore -> db -> strEscape( $smiley_replace) . '\', \'' . $this -> appCore -> db -> strEscape( $smiley_image) . '\', \'' . $smiley_width . '\', \'' . $smiley_height . '\', \'' . $this -> appCore -> db -> strEscape( $smiley_name) . '\', \'' . $smiley_in_editor . '\'';
								
									// Make file
									file_put_contents( SMILEYS_PATH . $smiley_image, $smiley_file);
								}
							}
						}
					}
				}
			}
			
			// Multiple insert?
			if ( !empty( $insert_sql))
			{
				$this -> appCore -> db -> multipleInsert( 'smiley_replace, smiley_image, smiley_width, smiley_height, smiley_name, smiley_in_editor', $insert_sql, 'smileys');
			}
			
			// Flush cache
			class_cache::flushCache('editor_data');
			class_cache::flushCache('parsing_data');
			
			// Set Log
			$this -> appCore -> logAdmin( 'log_admin_imported_smileys');
			
			// Stuff added, trow user to imagesets list
			$this -> appCore -> output -> drawRedirect( $this -> appCore -> adminLink( 'act=smileys'), $this -> appCore -> lang['acp_smileys_imported']);			
		}
		catch ( exc_small $error)
		{
			// Draw error
			$this -> appCore -> output -> error( $error -> message, $this -> appCore -> lang['acp_smileys_impexp']);
			
			// Repeat form
			$this -> drawForms();
		}
		
	}
	
	// ------------------------------------------------------------------------

	/**
	 * Performs Export
	 *
	 */
	
	function makeExport(){
		
		// Start content
		$file_content = '<?xml version="1.0" encoding="UTF-8"?>
<uniboard_smileys_export>
	<smileys>';
			
		// Select Smileys from DB
		$this -> appCore -> db -> query( 'SELECT * FROM ' . DB_PREFIX . 'smileys ORDER BY smiley_replace ASC');
		
		// Use result to export smileys
		while ( $smiley_result = $this -> appCore -> db -> fetch_array())
		{
			// File exists?
			if ( file_exists( SMILEYS_PATH . $smiley_result[2]))
			{
					// Add smiley
					$file_content .= '
		<smiley>
			<smiley_replace>' . base64_encode( $smiley_result[1]) . '</smiley_replace>
			<smiley_image>' . base64_encode( $smiley_result[2]) . '</smiley_image>
			<smiley_file>' . base64_encode( file_get_contents( SMILEYS_PATH . $smiley_result[2])) . '</smiley_file>
			<smiley_width>' . base64_encode( $smiley_result[3]) . '</smiley_width>
			<smiley_height>' . base64_encode( $smiley_result[4]) . '</smiley_height>
			<smiley_name>' . base64_encode( $smiley_result[5]) . '</smiley_name>
			<smiley_in_editor>' . base64_encode( $smiley_result[6]) . '</smiley_in_editor>
		</smiley>';
			}
		}
		
		// Close content
		$file_content .= '
	</smileys>
</uniboard_smileys_export>';
		
		// Set Log
		$this -> appCore -> logAdmin( 'log_admin_exported_smileys');
				
		// Compress it with GZIP?
		if ( function_exists( 'gzencode'))
		{
			// Compress file with gzip
			$file_content = gzencode( $file_content, 9);
			
			// Send non-compressed XML file
			$this -> appCore -> fileHeaders( 'application/x-compressed', strlen( $file_content), $this -> appCore -> secureFilename( PRODUCT_NAME) . '_Smileys' . '.xml.gz');
			
			// Echo file content
			echo ( $file_content);
		}
		else
		{
			// Send non-compressed XML file
			$this -> appCore -> fileHeaders( 'application/xml', strlen( $file_content), $this -> appCore -> secureFilename( PRODUCT_NAME) . '_Smileys' . '.xml');
			
			// Echo file content
			echo( $file_content);
		}
		
	}
	
	// ------------------------------------------------------------------------

	/**
	 * Draws Import and Export Forms
	 *
	 */
	
	function drawForms(){
			
		// Load fields templates
		$this -> appCore -> templates['form_inputs'] = new tpl_form_inputs( $this -> appCore);
		
		// Cache output
		ob_start();
		
		// Start Import Form
		echo $this -> appCore -> output -> openForm( $this -> appCore -> adminLink( 'act=smileys_impexp'), '', true);
		echo $this -> appCore -> output -> openFormBlock( $this -> appCore -> lang['impexp_smiley_import']);
		
		// Draw Fields
		echo $this -> appCore -> output -> formItem( $this -> appCore -> lang['import_smileys_file'], $this -> appCore -> drawFileUpload( 'data_file'), $this -> appCore -> lang['import_smileys_file_expl']);
		echo $this -> appCore -> drawHidden( 'import', 1);
		echo $this -> appCore -> output -> formItem( $this -> appCore -> lang['import_imageset_file'], $this -> appCore -> drawList( 'collisions_mode', array(
			0 => $this -> appCore -> lang['import_collisions_0'],
			1 => $this -> appCore -> lang['import_collisions_1'],
			2 => $this -> appCore -> lang['import_collisions_2']
		)), $this -> appCore -> lang['import_imageset_file_expl']);
		
		// Close Form
		echo $this -> appCore -> output -> submitButton( $this -> appCore -> lang['import_data']);
		echo $this -> appCore -> output -> closeFormBlock();
		echo $this -> appCore -> output -> closeForm();
		
		// ------------------------------------------------------------------------

		// Start Export Form
		echo $this -> appCore -> output -> openForm( $this -> appCore -> adminLink( 'act=smileys_impexp'));
		echo $this -> appCore -> drawHidden( 'export', 1);
		echo $this -> appCore -> output -> openFormBlock( $this -> appCore -> lang['impexp_smiley_export']);
		
		// Close Form
		echo $this -> appCore -> output -> submitButton( $this -> appCore -> lang['export_data']);
		echo $this -> appCore -> output -> closeFormBlock();
		echo $this -> appCore -> output -> closeForm();
		
		// Draw output
		$this -> appCore -> output -> draw( $this -> appCore -> lang['acp_smileys_impexp'], array( $this -> appCore -> adminLink( 'act=smileys_impexp') => $this -> appCore -> lang['acp_smileys_impexp']), ob_get_clean());
	
	}
	
}